package filter.script.pre

import com.alibaba.fastjson.JSONObject
import com.homedo.microservice.open.service.gateway.zuul.constant.ZuulConstant
import com.netflix.config.DynamicPropertyFactory
import com.netflix.config.DynamicStringProperty
import com.netflix.zuul.ZuulFilter
import com.netflix.zuul.context.Debug
import com.netflix.zuul.context.RequestContext
import org.slf4j.Logger
import org.slf4j.LoggerFactory

public class VersionPreFilter extends ZuulFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(VersionPreFilter.class);

    private static final DynamicStringProperty VERSION_ROUTE_PARAMETER = DynamicPropertyFactory
            .getInstance().getStringProperty(ZuulConstant.ZUUL_ROUTE_VERSION_PARAMETER, "routeVersion");


    @Override
    String filterType() {
        return "pre"
    }

    @Override
    int filterOrder() {
        return -999
    }

    @Override
    boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        Boolean isAccessedVersionPreFilter = requestContext.get(ZuulConstant.ZUUL_IS_ACCESSED_ROUTE_VERSION_FILTER);
        if (isAccessedVersionPreFilter != null && isAccessedVersionPreFilter) {
            return false;
        }

        String routeVersion = requestContext.getRequest().getParameter(VERSION_ROUTE_PARAMETER.get());
        if (routeVersion == null || routeVersion.length() == 0) {
            routeVersion = requestContext.getRequest().getHeader(VERSION_ROUTE_PARAMETER.get());
        }
        if (routeVersion == null || routeVersion.length() == 0) {
            Debug.addRequestDebug("经过VersionPreFilter:[请求中版本为空]");

//            if (requestContext.debugRequest()) {
//                LOGGER.info("[请求中版本为空]");
//            }
            return false;
        }

        return true;
    }

    @Override
    Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();

        String routeVersion = requestContext.getRequest().getParameter(VERSION_ROUTE_PARAMETER.get());
        if (routeVersion == null || routeVersion.length() == 0) {
            routeVersion = requestContext.getRequest().getHeader(VERSION_ROUTE_PARAMETER.get());
        }

        Debug.addRequestDebug("经过VersionPreFilter:[通过版本过滤配置，添加转发路由配置:" + routeVersion + "]");

//        if (requestContext.debugRequest()) {
//            LOGGER.info("[通过版本过滤配置，添加转发路由配置:{}]", routeVersion);
//        }

        String routeAddPrefix = requestContext.get(ZuulConstant.ZUUL_ROUTE_ADD_PREFIX);
        if (routeAddPrefix != null && routeAddPrefix.length() > 0) {
            routeAddPrefix = routeAddPrefix + ZuulConstant.ZUUL_ROUTE_ADD_PREFIX_SPLIT + routeVersion;
        } else {
            routeAddPrefix = routeVersion;
        }

        requestContext.put(ZuulConstant.ZUUL_ROUTE_ADD_PREFIX, routeAddPrefix);
        requestContext.put(ZuulConstant.ZUUL_IS_ACCESSED_ROUTE_VERSION_FILTER, true);
        return Boolean.TRUE;
    }

}
